package com.wpf.system.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wpf.system.common.response.ResultUtils;
import com.wpf.system.common.response.ResultVO;
import com.wpf.system.entity.Times;
import com.wpf.system.mapper.TimesMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/times")
public class TimesController {

    @Resource
    private TimesMapper timesMapper;

    @GetMapping
    public List<Times> getTimes(){
        return timesMapper.selectList(new LambdaQueryWrapper<Times>().orderByAsc(Times::getSort).orderByDesc(Times::getCreateTime));
    }

    @PreAuthorize("hasAuthority('sys:dictionary:time')")
    @PostMapping
    public ResultVO addTimes(@RequestBody Times times){
        if(Convert.toBool(timesMapper.insert(times))){
            return ResultUtils.success("添加新场馆开放时间段成功！");
        }else{
            return ResultUtils.error("添加新场馆开放时间段失败！");
        }
    }

    @PreAuthorize("hasAuthority('sys:dictionary:time')")
    @PutMapping
    public ResultVO editTimes(@RequestBody Times times){
        if(Convert.toBool(timesMapper.updateById(times))){
            return ResultUtils.success("修改场馆开放时间段名称成功！");
        }else{
            return ResultUtils.error("修改场馆开放时间段名称失败！");
        }
    }

    @PreAuthorize("hasAuthority('sys:dictionary:time')")
    @PutMapping("/sort")
    public ResultVO sortTimes(@RequestBody List<Times> timeslist){
        int count = 0;
        for(Times times : timeslist){
            count += timesMapper.updateById(times);
        }
        if(count==timeslist.size()){
            return ResultUtils.success("排序成功！");
        }else{
            return ResultUtils.error("排序失败！请重试！");
        }
    }

    @PreAuthorize("hasAuthority('sys:dictionary:time')")
    @DeleteMapping("/{id}")
    public ResultVO deleteTimes(@PathVariable("id") Long id){
        if(Convert.toBool(timesMapper.deleteById(id))){
            return ResultUtils.success("删除场馆开放时间段成功！");
        }else{
            return ResultUtils.error("删除场馆开放时间段失败！");
        }
    }
}
